// curl -k5/wx/login
const http = require('http');
const https = require('https');

//雪花算法生成
const Snowflake = require('./snowflack')

const SQLHelper = require('./SQLHepler')

const {formatTime}=require('./util')

const multer  = require('multer')
const storage = multer.diskStorage({
  destination:'./uploads',
  filename: function (req, file, cb) {
    //获取图片类型
    let fileType=file.originalname.split('.')
    fileType=fileType[fileType.length-1]
   
    cb(null, Snowflake() + '.' + fileType)
  }
})

const upload = multer({ storage: storage })



module.exports = function (app) {

  function loginRouter(req, res, next) {
    if (req.method.toUpperCase() == 'OPTIONS') {
      next()
      return
  }
    //登录拦截中间件
    let token = req.headers.token

    if (token) {
      SQLHelper(`select * from session where id=${token} and state=1`).then(ret => {
        if (ret.length) {
          let session = ret[0]
     
              //限制2H
              if(new Date().getTime()- session.createTime < 2*60*60*1000 ){
                req.session = {
                  userId: session.userId,
                  userName: session.userName
                }
                next()
              }else{
                res.status(400).send({ errorMsg: '登录已过期，请重新登录' })
              }

      
        } else {
          res.status(400).send({ errorMsg: '当前用户未登录' })
        }
      })
    }
    else {
      res.status(400).send({ errorMsg: '缺少token,请先登录' })
    }

  }

  //让初登录的所有小程序接口先验证登录
  app.use('/admin', loginRouter)


  //后台登录
  app.post('/login', (req, res, next) => {
      let userName=req.body.userName
      let passWord=req.body.passWord
      if(userName && passWord){
          SQLHelper(`
          select * from user where userName='${userName}'
          `).then(users =>{
            if(users.length){//正常登录
              let user=users[0]

              if(passWord==user.passWord){
                let token = Snowflake()
                
                //缓存到tokens 到session表
            
                SQLHelper(`
              INSERT INTO session (id,userId,userName,inTime,createTime,platform)  VALUES 
              (${token},'${user._id}','${user.nickName}','${formatTime(new Date())}','${new Date().getTime()}','admin')
              `).then(ret => {
                  res.send({
                    nickName: user.nickName,
                    token,
                    avatarUrl:user.phone,
                    _id: user._id
                  })
                })
              }else{
                res.send({errorMsg:'密码错误'})
              }
            }else{
              res.send({errorMsg:'当前用户不存在'})
            }
          })
      }else{
        res.send({errorMsg:'用户名和密码不能为空!'})
      }
  })

  //退出登录
  app.get('/admin/logout',(req,res)=>{
    SQLHelper(`
    update session set outTime='${formatTime(new Date())}', state=0
    where id= ${req.headers.token}
    `).then(ret =>{
    res.send({msg:'退出登录成功'})
  })
  })

  //修改密码
  app.post('/admin/changePassWord',(req,res)=>{
    let userId=req.session.userId
    let passWord=req.body.passWord
    let newPassWord=req.body.newPassWord

    if(passWord && newPassWord){
      //查询用户
         SQLHelper(`
      select passWord from user where _id='${userId}'
    `).then(users =>{
      let user =users[0]
      //比对原密码
      if(user.passWord==passWord){
        //修改密码
        SQLHelper(`
        update user set passWord='${newPassWord}' where _id='${userId}'
      `).then(ret =>{
        res.send({msg:'修改密码成功'})
      })

      }else{
        res.send({errorMsg:'原密码错误'})
      }
   
  })
    }else{
      res.send({errorMsg:'原密码和新密码不能为空'})
    }
 
  })
  //////////////////////////////////////////////首页

  //获取首页轮播图
  //pageSize每页数据大小默认10  pageNum当前页默认1
  app.get('/admin/index',(req,res)=>{
    let pageSize=req.query.pageSize || 10
    let pageNum=req.query.pageNum || 1
    let offset=(pageNum - 1)* pageSize
    let type=req.query.type
    let title=req.query.title
    let whereSql='from index_region where state=1'

    //按类型chaxun
    if(type) whereSql +=` and type ='${type}'`

    //按关键字搜索
    if(title) whereSql  +=` and title like "%${title}%"`
    SQLHelper(`
        select count(*) as total ${whereSql};
        select * ${whereSql} limit ${pageSize} offset ${offset}
      `).then(ret =>{
        res.send({
          total:ret[0][0].total,
          rows:ret[1]
        })
      })
  })

  //新增首页项目
  //必填 img 图片地址 
  //非必填 url链接地址 status是否启用1启用0禁用 type类型 banner,category,recommend title轮播不填其他必填
  app.post('/admin/index', (req, res) => {
    let img=req.body.img,url=req.body.url,status=req.body.status,type=req.body.type || 'banner',title=req.body.title 
    if(type !='banner' && !title){
      res.send({errorMsg:'标题不能为空'})
      return
    }
    if(status !=1) status=0//默认启用

    if (img) {
      let createTime= new Date().getTime()
      SQLHelper(`
    INSERT INTO index_region (title,img,url,status,state,createTime,unitId,type)  VALUES 
    ('${title}','${img}','${url}','${status}',1,'${createTime}','juzao','${type}')
    `).then(ret => {
      let _id=ret.insertId
        res.send(ret.insertId ? {_id:ret.insertId} : {errorMsg:'新增数据失败'})
      })
    }
    else {
      res.send({ errorMsg: '请求参数错误' })
    }

  })

   //修改首页项目
  //必填indexId _id 
  app.put('/admin/index', (req, res) => {

    if (req.body.indexId) {
      let updateTime=new Date().getTime()
      let updatekey = ['img', 'url', 'title', 'status']
      let updateValues = [`updateTime=${updateTime}`]

      for (let i = 0; i < updatekey.length; i++) {
        let key = updatekey[i], value = req.body[key]
        if (value !==undefined) updateValues.push(`${key}='${value}'`)

      }

      SQLHelper(`
    update index_region set ${updateValues.join(',')} where _id = ${req.body.indexId}
    `).then(ret => {
        res.send(ret)
      })
    }
    else {
      res.send({ errorMsg: '传入参数错误' })
    }

  })

   //删除首页项目 逻辑
   app.delete('/admin/index', (req, res) => {
    let indexId = req.query.indexId
    if (indexId) {
      SQLHelper(`
    UPDATE index_region SET state =0  where _id='${indexId}'
    `).then(ret => {
        res.send(ret)
      })
    }

    else {
      res.send({ errorMsg: '请求参数错误' })
    }
  })

  /////////////////////////////////////////////////////////新闻

  //获取新闻
  app.get('/admin/index/news',(req,res)=>{
    let pageSize=req.query.pageSize || 10
    let pageNum=req.query.pageNum || 1
    let offset=(pageNum - 1)* pageSize
    let type=req.query.type
    let title=req.query.title
    let whereSql='from article where state=1'

    //按类型chaxun
    if(type) whereSql +=` and type ='${type}'`

    //按关键字搜索
    if(title) whereSql  +=` and title like "%${title}%"`
    SQLHelper(`
        select count(*) as total ${whereSql};
        select * ${whereSql} limit ${pageSize} offset ${offset}
      `).then(ret =>{
        res.send({
          total:ret[0][0].total,
          rows:ret[1]
        })
      })
  })



   //新增新闻
  app.post('/admin/index/news', (req, res) => {
    let img=req.body.img,digest=req.body.digest,status=req.body.status,type=req.body.type || 'news',title=req.body.title 
    if(type !='news' && !title){
      res.send({errorMsg:'标题不能为空'})
      return
    }
    if(status !=1) status=0//默认启用

    if (img) {
      let createTime= new Date().getTime()
      SQLHelper(`
    INSERT INTO article (title,img,digest,status,state,createTime,unitId,type)  VALUES 
    ('${title}','${img}','${digest}','${status}',1,'${createTime}','juzao','${type}')
    `).then(ret => {
      let _id=ret.insertId
        res.send(ret.insertId ? {_id:ret.insertId} : {errorMsg:'新增数据失败'})
      })
    }
    else {
      res.send({ errorMsg: '请求参数错误' })
    }

  })

   

   //修改新闻
  app.put('/admin/index/news', (req, res) => {

    if (req.body.indexId) {
      let updateTime=new Date().getTime()
      let updatekey = ['img', 'digest', 'title', 'status']
      let updateValues = [`updateTime=${updateTime}`]

      for (let i = 0; i < updatekey.length; i++) {
        let key = updatekey[i], value = req.body[key]
        if (value !==undefined) updateValues.push(`${key}='${value}'`)

      }

      SQLHelper(`
    update article set ${updateValues.join(',')} where _id = ${req.body.indexId}
    `).then(ret => {
        res.send(ret)
      })
    }
    else {
      res.send({ errorMsg: '传入参数错误' })
    }

  })

   

    //删除新闻
    app.delete('/admin/index/news', (req, res) => {
      let indexId = req.query.indexId
      if (indexId) {
        SQLHelper(`
      UPDATE article SET state =0  where _id='${indexId}'
      `).then(ret => {
          res.send(ret)
        })
      }
  
      else {
        res.send({ errorMsg: '请求参数错误' })
      }
    })
  ///////////////////////////////////////////////////////////品牌

      //获取品牌
  app.get('/admin/index/brand',(req,res)=>{
    let pageSize=req.query.pageSize || 10
    let pageNum=req.query.pageNum || 1
    let offset=(pageNum - 1)* pageSize
    let type=req.query.type
    let name=req.query.name
    let whereSql='from brand where state=1'

    //按类型chaxun
    if(type) whereSql +=` and type ='${type}'`

    //按关键字搜索
    if(name) whereSql  +=` and name like "%${name}%"`
    SQLHelper(`
        select count(*) as total ${whereSql};
        select * ${whereSql} limit ${pageSize} offset ${offset}
      `).then(ret =>{
        res.send({
          total:ret[0][0].total,
          rows:ret[1]
        })
      })
  })

   //新增品牌
   app.post('/admin/index/brand', (req, res) => {
    let img=req.body.img,name=req.body.name,status=req.body.status,type=req.body.type || 'brand'
    if(type !='brand' && !name){
      res.send({errorMsg:'品牌名不能为空'})
      return
    }
    if(status !=1) status=0//默认启用

    if (img) {
      let createTime= new Date().getTime()
      SQLHelper(`
    INSERT INTO brand (img,name,status,state,createTime,unitId,type)  VALUES 
    ('${img}','${name}','${status}',1,'${createTime}','juzao','${type}')
    `).then(ret => {
      let _id=ret.insertId
        res.send(ret.insertId ? {_id:ret.insertId} : {errorMsg:'新增数据失败'})
      })
    }
    else {
      res.send({ errorMsg: '请求参数错误' })
    }

  })

     //修改品牌
     app.put('/admin/index/brand', (req, res) => {

      if (req.body.indexId) {
        let updateTime=new Date().getTime()
        let updatekey = ['img',  'name', 'status']
        let updateValues = [`updateTime=${updateTime}`]
  
        for (let i = 0; i < updatekey.length; i++) {
          let key = updatekey[i], value = req.body[key]
          if (value !==undefined) updateValues.push(`${key}='${value}'`)
  
        }
  
        SQLHelper(`
      update brand set ${updateValues.join(',')} where _id = ${req.body.indexId}
      `).then(ret => {
          res.send(ret)
        })
      }
      else {
        res.send({ errorMsg: '传入参数错误' })
      }
  
    })
  
     
  
      //删除品牌
      app.delete('/admin/index/brand', (req, res) => {
        let indexId = req.query.indexId
        if (indexId) {
          SQLHelper(`
        UPDATE brand SET state =0  where _id='${indexId}'
        `).then(ret => {
            res.send(ret)
          })
        }
    
        else {
          res.send({ errorMsg: '请求参数错误' })
        }
      })

      //////////////////////////////////////////////////////////商品


    //获取商品
    app.get('/admin/index/product',(req,res)=>{
      let pageSize=req.query.pageSize || 10
      let pageNum=req.query.pageNum || 1
      let offset=(pageNum - 1)* pageSize
      let type=req.query.type
      let name=req.query.name
      let whereSql='from product where state=1'
  
      //按类型chaxun
      if(type) whereSql +=` and type ='${type}'`
  
      //按关键字搜索
      if(name) whereSql  +=` and name like "%${name}%"`
      SQLHelper(`
          select count(*) as total ${whereSql};
          select * ${whereSql} limit ${pageSize} offset ${offset}
        `).then(ret =>{
          res.send({
            total:ret[0][0].total,
            rows:ret[1]
          })
        })
    })
  
     //新增商品
     app.post('/admin/index/product', (req, res) => {
      let img=req.body.img,name=req.body.name,status=req.body.status,type=req.body.type || 'product'
      let brandId=req.body.brandId,description=req.body.description,specification=req.body.specification,sales=req.body.sales,functionality=req.body.functionality
      if(type !='product' && !name){
        res.send({errorMsg:'商品名不能为空'})
        return
      }
      if(status !=1) status=0//默认启用
  
      if (img) {
        let createTime= new Date().getTime()
        SQLHelper(`
      INSERT INTO product (img,name,brandId,description,specification,sales,functionality,status,state,createTime,unitId,type)  VALUES 
      ('${img}','${name}','${brandId}','${description}','${specification}','${sales}','${functionality}','${status}',1,'${createTime}','juzao','${type}')
      `).then(ret => {
        let _id=ret.insertId
          res.send(ret.insertId ? {_id:ret.insertId} : {errorMsg:'新增数据失败'})
        })
      }
      else {
        res.send({ errorMsg: '请求参数错误' })
      }
  
    })
  
       //修改商品
       app.put('/admin/index/product', (req, res) => {
  
        if (req.body.indexId) {
          let updateTime=new Date().getTime()
          let updatekey = ['img','name','brandId','description','specification','sales','functionality', 'status']
          let updateValues = [`updateTime=${updateTime}`]
    
          for (let i = 0; i < updatekey.length; i++) {
            let key = updatekey[i], value = req.body[key]
            if (value !==undefined) updateValues.push(`${key}='${value}'`)
    
          }
    
          SQLHelper(`
        update product set ${updateValues.join(',')} where _id = ${req.body.indexId}
        `).then(ret => {
            res.send(ret)
          })
        }
        else {
          res.send({ errorMsg: '传入参数错误' })
        }
    
      })
    
       
    
        //删除商品
        app.delete('/admin/index/product', (req, res) => {
          let indexId = req.query.indexId
          if (indexId) {
            SQLHelper(`
          UPDATE product SET state =0  where _id='${indexId}'
          `).then(ret => {
              res.send(ret)
            })
          }
      
          else {
            res.send({ errorMsg: '请求参数错误' })
          }
        })


        ////////////////////////////////////////////////////分类


         //获取分类
    app.get('/admin/index/classify',(req,res)=>{
      let pageSize=req.query.pageSize || 10
      let pageNum=req.query.pageNum || 1
      let offset=(pageNum - 1)* pageSize
      let type=req.query.type
      let name=req.query.name
      let whereSql='from category where state=1'
  
      //按类型chaxun
      if(type) whereSql +=` and type ='${type}'`
  
      //按关键字搜索
      if(name) whereSql  +=` and name like "%${name}%"`
      SQLHelper(`
          select count(*) as total ${whereSql};
          select * ${whereSql} limit ${pageSize} offset ${offset}
        `).then(ret =>{
          res.send({
            total:ret[0][0].total,
            rows:ret[1]
          })
        })
    })
  
     //新增分类
     app.post('/admin/index/classify', (req, res) => {
      let img=req.body.img,name=req.body.name,status=req.body.status,type=req.body.type || 'classify'
      let parentId=req.body.parentId,level=req.body.level,sort=req.body.sort
      if(type !='classify' && !name){
        res.send({errorMsg:'分类名不能为空'})
        return
      }
      if(status !=1) status=0//默认启用
  
      if (img) {
        let createTime= new Date().getTime()
        SQLHelper(`
      INSERT INTO category (img,name,parentId,level,sort,status,state,createTime,unitId,type)  VALUES 
      ('${img}','${name}','${parentId}','${level}','${sort}','${status}',1,'${createTime}','juzao','${type}')
      `).then(ret => {
        let _id=ret.insertId
          res.send(ret.insertId ? {_id:ret.insertId} : {errorMsg:'新增数据失败'})
        })
      }
      else {
        res.send({ errorMsg: '请求参数错误' })
      }
  
    })
  
       //修改分类
       app.put('/admin/index/classify', (req, res) => {
  
        if (req.body.indexId) {
          let updateTime=new Date().getTime()
          let updatekey = ['img','name','parentId','level','sort']
          let updateValues = [`updateTime=${updateTime}`]
    
          for (let i = 0; i < updatekey.length; i++) {
            let key = updatekey[i], value = req.body[key]
            if (value !==undefined) updateValues.push(`${key}='${value}'`)
    
          }
    
          SQLHelper(`
        update category set ${updateValues.join(',')} where _id = ${req.body.indexId}
        `).then(ret => {
            res.send(ret)
          })
        }
        else {
          res.send({ errorMsg: '传入参数错误' })
        }
    
      })
    
       
    
        //删除分类
        app.delete('/admin/index/classify', (req, res) => {
          let indexId = req.query.indexId
          if (indexId) {
            SQLHelper(`
          UPDATE category SET state =0  where _id='${indexId}'
          `).then(ret => {
              res.send(ret)
            })
          }
      
          else {
            res.send({ errorMsg: '请求参数错误' })
          }
        })

  
////////////////////////////////////////////////////////文件上传
    //文件上传
    app.post('/upload',upload.single('file'),(req,res)=>{
      res.send(req.file)
    })

 
}

